"use strict";

Components.utils.import("resource://gre/modules/Services.jsm")
Components.utils.import("chrome://viewsosource/locale/utility.jsm")

const prefEditorPath = "view_source.editor.path"
const prefEditorArgs = "view_source.editor.args"
const tooltipTextBtn = { accept: "<Enter>", cancel: "<Esc>" }
  //    view_source.editor.args prefEditorPath

    // Returns nsIProcess of the external view source editor or null
    //   gViewSourceUtils.viewSourceProgressListener.onContentLoaded = function()

 gViewSourceUtils.viewSourceProgressListener.onStateChange =
 function(aProgress, aRequest, aFlag, aStatus)
 {
    if (aFlag & this.mnsIWebProgressListener.STATE_STOP)
    if(aStatus)
    {
        window.setTimeout(
            function(aURL, aPageDescriptor, aDocument)
            {
                top.gViewSourceUtils.openInInternalViewer(aURL, aPageDescriptor, aDocument, 0);
            }, 0, this.data.url,
                this.data.pageDescriptor,
                this.data.doc );
    }
    else
    {
        var thesave = Services.prefs.getCharPref(prefEditorArgs);
        var preargs = document.getElementById("editorCmdargs").value;
        try {
            Services.prefs.setCharPref(prefEditorArgs, preargs);
            gViewSourceUtils.viewSourceProgressListener.onContentLoaded();
        }
        finally {
            Services.prefs.setCharPref(prefEditorArgs, thesave);
        }
    }
    return 0;
 }

// Returns nsIProcess of the external view source editor or null
//    getExternalViewSourceEditor: function()
//  buildEditorArgs: function(aPath, aLineNumber) {
var viewSoso = {    //  from overlay.xul\js
//    tagName     : "view-so-source:chrome,titlebar,centerscreen,modal",
    viewSrcUrl  : "about:home",
    charset     : null,

//  gViewSourceUtils.getExternalViewSourceEditor
    orgExternalViewSourceEditor : null,

 overrideExtEditor : function()
{
    var editor  = null;
    var thesave = Services.prefs.getCharPref(prefEditorPath);
    var prepath = document.getElementById("editorApps").value;
    var therr = { name: "NS_ERROR_FILE_EXECUTION_FAILED", code : 0x80520003 };
    try {
        let viewSourceAppPath = Components.classes["@mozilla.org/file/local;1"]
                        .createInstance(Components.interfaces.nsIFile);
            viewSourceAppPath.initWithPath(prepath);
        if(viewSourceAppPath.isExecutable())
        try {
            Services.prefs.setCharPref(prefEditorPath, prepath);
            editor = viewSoso.orgExternalViewSourceEditor();
            viewSourceAppPath = null;
        }
        finally
        {
            Services.prefs.setCharPref(prefEditorPath, thesave);
        }
    }
    catch (err)
    {
        editor = null;
        therr = err;
        Components.utils.reportError(err);
    }

    if(!editor) viewSoso.alert(therr);
    return editor;    
},

 woman : function(aself) // prefwindow.onload
{
    var thedlg = document.getElementById("pref-dlg");
    var thebox = document.querySelector("hbox.resizer");  //  getElementById("boxResizer");
    if((thedlg) && (thebox))
    {
        let thebtn = thedlg.getButton("accept");
            thebtn.parentNode.appendChild(thebox);
            thebtn.tooltipText = tooltipTextBtn["accept"];
        thedlg.getButton("extra1").addEventListener("mouseenter", viewSoso.enterTest, false);
        thedlg.getButton("cancel").tooltipText = tooltipTextBtn["cancel"];
    }

    viewSoso.back2front(aself); // set input fields
},

 alert : function(err)
 {
//    var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
//                    .getService(Components.interfaces.nsIPromptService);
    if(err.name in moduleViewSoso.errmsg)
        Services.prompt.alert(window, err.name, moduleViewSoso.errmsg[err.name])
    else
        if(document.getElementById("editorApps").value)
            Services.prompt.alert(window, err.name, err.message)
        else
            Services.prompt.alert(window, err.name, moduleViewSoso.empty);
 },

//  1. move resizer to hbox.prefWindow-dlgbuttons
//  2. copy preference to front:
//      "editorCmdargs" viewerCmdargs
//      editorApps      viewerApps
 back2front : function (aself)
{
    var thepicker = document.getElementById("editorApps");
    if(thepicker)
    try {    
        document.getElementById("editorCmdargs").value = 
            document.getElementById("viewerCmdargs").value;
        thepicker.value = document.getElementById("viewerApps").value;

        var theval = thepicker.getAttribute("tooltiptext");
            thepicker.removeAttribute("tooltiptext");
            thepicker.textbox.setAttribute("tooltiptext", theval);
    
        if(document.getElementById("prefExternal").value)
            thepicker.disabled = false;
    }
    catch (err) {
        Components.utils.reportError(err)
    }
},

 front2back : function (aself)
{
    var theback = document.getElementById("viewerCmdargs");
    theback.value = document.getElementById("editorCmdargs").value;
    theback.doCommand();
    
        theback = document.getElementById("viewerApps");
    theback.value = document.getElementById("editorApps").value;
    theback.doCommand();
},

    // Determine the command line arguments to pass to the editor.
    // We currently support a %LINE% placeholder which is set
    //  to the passed line number (or to 0 if there's none)
 buildEditorArgs: function(anpath, anargs)
{
    const argumentRE = /"([^"]+)"|(\S+)/g;
    var editorArgs = [];
    if (anargs) {
      anargs = anargs.replace("%LINE%", "0");
    //    dump("_dvk_dbg_, args:\t"); dump(anargs); dump("\n");
    // add the arguments to the array (keeping quoted strings intact)
        while (argumentRE.test(anargs))
            editorArgs.push(RegExp.$1 || RegExp.$2);
    }
    editorArgs.push(anpath);
    return editorArgs;
},

 enterTest : function(anevent)
{
    var thapp = document.getElementById("editorApps").value;
    var thargs = document.getElementById("editorCmdargs").value;
        thargs = viewSoso.buildEditorArgs(viewSoso.viewSrcUrl, thargs);
    anevent.currentTarget.tooltipText = [ thapp, thargs.join(" ") ].join(" ");
},

 setbtnFilepicker : function (aself)
{
    document.getElementById("editorApps").disabled = !(aself.value);
},

    //  url: aURL, pageDescriptor: aPageDescriptor, doc: aDocument,
//    gViewSourceUtils.openAppendixEditor(viewSoso.viewSrcUrl, viewSoso.charset);
//    gViewSourceUtils.openInExternalEditor(viewSoso.viewSrcUrl, null, null, 0);
 openTest : function()
{
    //  record up default behavior that call .internalViewerFallback
  var thecallback = function(aresult, adata) { }

    var thesave = Services.prefs.getCharPref(prefEditorArgs);
    var preargs = document.getElementById("editorCmdargs").value;
    try {
        Services.prefs.setCharPref(prefEditorArgs, preargs);
        gViewSourceUtils.openInExternalEditor(
            viewSoso.viewSrcUrl, null, null, 0, thecallback );
    }
    finally {
        Services.prefs.setCharPref(prefEditorArgs, thesave);
    }
},

}   //  viewSoso
